﻿using _111.Models;
using _111.QywxDocument.WeeklyReport.Model;
using Google.Protobuf.WellKnownTypes;
using guidHelper;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using MyDapperApi.Models;
using MyDapperApi.Services.BaiLianAI;
using MyDapperApi.Services.QywxBase;
using Mysqlx.Crud;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.CheckInfo;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using static MyDapperApi.Services.DateBaseService;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace MyDapperApi.Services.ConsumerNum;

public class ConsumerNumService : IConsumerNumService
{
    private readonly IConfiguration _configuration;
    private readonly IDateBaseService _dateBaseService;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IBaiLianAIBaseService _biLianAIBaseService;
    private readonly IQywxBaseService _iqywxBaseService;

    public ConsumerNumService(IConfiguration configuration,
        IDateBaseService dateBaseService,
        IHttpClientFactory httpClientFactory,
        IBaiLianAIBaseService biLianAIBaseService,
        IQywxBaseService qywxBaseService)
    {
        _configuration = configuration;
        _dateBaseService = dateBaseService;
        _httpClientFactory = httpClientFactory;
        _biLianAIBaseService = biLianAIBaseService;
        _iqywxBaseService = qywxBaseService;
    }


    public async Task<CommonResponse> UpdateConsumerNum(DateTime dateTime,string pmsId,string key)
    {
        var result = new CommonResponse();

        //数据库查询需要推送的人员
        var roles = GetTargetRole();

        //数据库查询推送的数据
        var sgConsumerNum = await GetData(0,pmsId);
        var qsConsumerNum = await GetData(1,pmsId);

        sgConsumerNum.AddRange(qsConsumerNum);

        // 优化后：控制并发度的并行请求
        var tasks = new List<Task<CommonResponse>>();

        // 使用 SemaphoreSlim 控制并发数量，避免瞬间发起几百个请求被防火墙拦截
        using (var semaphore = new SemaphoreSlim(10)) // 允许同时 10 个请求
        {
            var processTasks = sgConsumerNum.Select(async item =>
            {
                await semaphore.WaitAsync();
                try
                {
                    var content = new
                    {
                        msgtype = "markdown",
                        markdown = new
                        {
                            content = GenerateWeComMarkdown(item,dateTime),
                        }
                    };

                    var postContent = new StringContent(
                       JsonConvert.SerializeObject(content),
                       System.Text.Encoding.UTF8,
                       "application/json");

                    result = await PostComment(postContent, "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+key);
                }
                finally
                {
                    semaphore.Release();
                }
            });

            await Task.WhenAll(processTasks);
        }

        //var content = new
        //{
        //    msgtype = "markdown",
        //    markdown = new
        //    {
        //        content = consumerNum,
        //    }
        //};

        //var postContent = new StringContent(
        //   JsonConvert.SerializeObject(content),
        //   System.Text.Encoding.UTF8,
        //   "application/json");

        ////执行企业微信推送

        //result = await PostComment(postContent, "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9a93bd54-7ade-4b5a-9a9a-b7c32aea41cc");

        return result;
    }

    /// <summary>
    /// 获取需要推送的人员数据
    /// </summary>
    /// <returns></returns>
    public async Task<List<CheckInfoRoleResponse>> GetTargetRole()
    {
        var result = new List<CheckInfoRoleResponse>();
        return result;
    }

    /// <summary>
    /// 获取目前在场的客流信息
    /// </summary>
    /// <param name="type">0水裹1曲水</param>
    /// <returns></returns>
    public async Task<List<ConsumerNumModel>> GetData(int type,string pmsId)
    {
        var result = new List<ConsumerNumModel>();

        var CustomerNo = string.Empty;
        var SqlData = string.Empty;

        if (type == 0)
        {
            CustomerNo = "XSHJT";
            SqlData = "SgSqlServerConnection";
        }
        if (type == 1)
        {
            CustomerNo = "XSHQS";
            SqlData = "QsSqlServerConnection";
        }

        var sql = string.Empty;
        var sqlBuilder = new SqlBuilder();

        sql = $@"select PmsID,
	SUM(ChildrenCount) + SUM(AdultCount) 'Total',
	SUM(CASE WHEN Sex = 'M' THEN AdultCount ELSE 0 END) AS Male,
    SUM(CASE WHEN Sex = 'F' THEN AdultCount ELSE 0 END) AS Female,
		Sum(ChildrenCount) AS Children
    FROM SpaCheckInfo
  where 1 = 1
	AND CustomerNo = '{CustomerNo}' 
	and PmsID = '{pmsId}' 
	and Status = 1 and RecordType=0 AND (GateStatus IS NULL OR GateStatus <>1)
	GROUP BY PmsID";

        result = await _dateBaseService.QueryAsync<ConsumerNumModel>(sql, sqlBuilder, 1, SqlData);

        //result = GenerateWeComMarkdownTotal(data);

        return result;
    }

    /// <summary>
    /// 创建推送服务推送数据(todo)
    /// </summary>
    /// <param name="role"></param>
    /// <param name="list"></param>
    /// <returns></returns>
    public async Task<CommonResponse> CreatePostDetail(CheckInfoRoleResponse role, List<ConsumerNumModel> list)
    {
        var result = new CommonResponse();

        var item = list.FirstOrDefault(item => item != null && item.PmsId == role.PmsId);//匹配了对应人物

        return result;
    }

    /// <summary>
    /// 暂时方法用于推送群聊消息--暂时不用
    /// </summary>
    public async Task CreateComment()
    {
        var item = new
        {
            name = "测试群聊",
            owner = "d3013725-f1dc-47b7-ab61-411b0b257e3b",
            chatid = "A10475",
            userlist = new List<string>()
            {
                "d3013725-f1dc-47b7-ab61-411b0b257e3b","18801315605"
            }
        };
        var content = new StringContent(
            JsonConvert.SerializeObject(item),
            System.Text.Encoding.UTF8,
            "application/json");

        var wxResponse = await _iqywxBaseService.QywxCommonPost<WXResponse>(content, "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token=");
    }

    public async Task<CommonResponse> PostComment(StringContent content, string url)
    {
        var result = new CommonResponse();

        var client = _httpClientFactory.CreateClient();

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        url,
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await ToolHelper.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXResponse>(res);
                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    result.SetSuccess(wxRespon);
                }
                return result;
            }

        }
        response.EnsureSuccessStatusCode();

        return result;
    }

    /// <summary>
    /// 创建markdown
    /// </summary>
    /// <param name="dataList"></param>
    /// <returns></returns>
    public string GenerateWeComMarkdownTotal(List<ConsumerNumModel> dataList)
    {
        if (dataList == null || dataList.Count == 0)
        {
            return "暂无消费者人数数据。";
        }

        StringBuilder sb = new StringBuilder();

        // 标题
        sb.AppendLine("## 👥 消费者人数统计报告");
        sb.AppendLine();
        sb.AppendLine($"> 本次共计统计 **{dataList.Count}** 个 店铺 数据。");
        sb.AppendLine("---"); // 分隔线

        foreach (var item in dataList)
        {
            // 使用引用块 (>) 突出显示每个 PMS 的数据
            sb.AppendLine($"> **门店名称**: <font color=\"info\">{GetName(item.PmsId)}</font>");
            // 总数用 warning 颜色高亮
            sb.AppendLine($"> **总人数**: <font color=\"warning\">{item.Total} 人</font>");

            // 详细分类使用 comment 颜色
            sb.AppendLine($"> > - 男士: <font color=\"comment\">{item.Male} 人</font>");
            sb.AppendLine($"> > - 女士: <font color=\"comment\">{item.Female} 人</font>");
            sb.AppendLine($"> > - 儿童: <font color=\"comment\">{item.Children} 人</font>");

            sb.AppendLine("---"); // 分隔线
        }

        // 移除最后一个分隔线，防止列表末尾多余
        if (sb.Length > 0 && sb.ToString().EndsWith("---" + Environment.NewLine))
        {
            sb.Length -= ("---" + Environment.NewLine).Length;
        }

        return sb.ToString();
    }

    /// <summary>
    /// 创建markdown
    /// </summary>
    /// <param name="dataList"></param>
    /// <returns></returns>
    public string GenerateWeComMarkdown(ConsumerNumModel item,DateTime dateTime)
    {
        if (item == null)
        {
            return "暂无消费者人数数据。";
        }

        StringBuilder sb = new StringBuilder();

        // 标题
        sb.AppendLine("## 👥 实时在场客流数据");
        sb.AppendLine();

        // 使用引用块 (>) 突出显示每个 PMS 的数据
        sb.AppendLine($"> **门店名称**: <font color=\"info\">{GetName(item.PmsId)}</font>");
        // 总数用 warning 颜色高亮
        sb.AppendLine($"> **总人数**: <font color=\"warning\">{item.Total} 人</font>");

        // 详细分类使用 comment 颜色
        sb.AppendLine($"> > - 男士: <font color=\"comment\">{item.Male} 人</font>");
        sb.AppendLine($"> > - 女士: <font color=\"comment\">{item.Female} 人</font>");
        sb.AppendLine($"> > - 儿童: <font color=\"comment\">{item.Children} 人</font>");

        if(item.PmsId != "xshqs06")
        {
            var entitys = GetPrivateRoomEntityList(item.PmsId, dateTime);

            if (entitys.Result.Count > 0)
            {
                foreach (var item1 in entitys.Result)
                {
                    sb.AppendLine($"> > - 已预订餐包: <font color=\"comment\">{item1.Private_Room}</font>");
                }
            }
            else
            {
                sb.AppendLine("未预定餐包");
            }
        }
        return sb.ToString();
    }

    public async Task<List<PrivateRoomEntity>> GetPrivateRoomEntityList(string shopId, DateTime date)
    {
        var result = new List<PrivateRoomEntity>();

        var startTime = date.Date.ToString("yyyy-MM-dd HH:mm:ss");
        var endTime = date.AddDays(1).Date.ToString("yyyy-MM-dd HH:mm:ss");

        var sql = string.Empty;
        var sqlBuilder = new SqlBuilder();
        sqlBuilder.Add("", "@ShopName", GetName(shopId));
        sqlBuilder.Add("", "@StartTime", startTime);
        sqlBuilder.Add("", "@EndTime", endTime);

        sql = $@"SELECT * FROM private_room WHERE 1 = 1
AND is_deleted = 0
AND shop_name = @ShopName
AND date >= @StartTime AND date < @EndTime;";

        result = await _dateBaseService.QueryAsync<PrivateRoomEntity>(sql, sqlBuilder, 0, "QywxDocument");

        return result;
    }

    public string GetName(string pmsId)
    {
        var result = string.Empty;

        switch (pmsId)
        {
            case "xshqs01":
                return "北京曲水";
                break;
            case "xshqs02":
                return "武汉曲水徐东店";
                break;
            case "xshqs03":
                return "杭州曲水";
                break;
            case "xshqs04":
                return "武汉曲水光谷店";
                break;
            case "xshqs05":
                return "苏州曲水";
                break;
            case "xshqs06":
                return "上海曲水";
                break;
            case "xshqs07":
                return "郑州曲水";
                break;
            case "xshsg01":
                return "上海水裹1店";
                break;
            case "xshsg02":
                return "上海水裹2店";
                break;
            case "xshsg03":
                return "北京水裹";
                break;
            case "xshsg04":
                return "北京水裹加";
                break;
            case "xshsg05":
                return "杭州水裹1店";
                break;
            case "xshsg06":
                return "杭州水裹2店";
                break;
            case "xshsg07":
                return "武汉水裹";
                break;
            case "xshsg08":
                return "常州水裹";
                break;
            case "xshsg09":
                return "深圳水裹";
                break;
            case "xshlx01":
                return "武汉兰栖";
                break;
        }

        return result;
    }
}